package apps.imgApp;

import backs.JSONChater.MyJSONSend;
import backs.Main;
import backs.tools.Tools;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

public class ImageCreater
{

    public static boolean createImg(String[] template,String text,String fileName)
    {
        File file = new File(Tools.getImagePath()+fileName);
        try {
            BufferedImage  inputImage = ImageIO.read(new File(template[0]));

            int width = inputImage.getWidth();
            int height =inputImage.getHeight();

            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = (Graphics2D)bi.getGraphics();
            g2.setBackground(Color.white);
            g2.clearRect(0, 0, width, height);
            g2.drawImage(inputImage,0,0,width,height,null);
            String[] colors=template[4].split(",");
            Color color=new Color(Integer.parseInt(colors[0]),Integer.parseInt(colors[1]),Integer.parseInt(colors[2]));
            g2.setPaint(color);


            Font font = new Font(template[5], Integer.parseInt(template[6]), Integer.parseInt(template[1]));
            g2.setFont(font);
            FontRenderContext context = g2.getFontRenderContext();
            Rectangle2D bounds = font.getStringBounds(text, context);
            double x = (width - bounds.getWidth()) / 2;
            double y = (height - bounds.getHeight()) / 2;
            double ascent = -bounds.getY();
            double baseY = y + ascent;

            g2.drawString(text, (int)(x+(Double.parseDouble(template[2])-0.5)*width), (int)(baseY+(Double.parseDouble(template[3])-0.5)*height));

            ImageIO.write(bi, "png", file);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            Main.addError("ImageCreater",e.getMessage());
            MyJSONSend.sendToMe(e.getMessage());
            return false;
        }
        return true;
    }
}
